#include "Character.h"
#include "Map.h"

Character::Character(void)
{
}

Character::~Character(void)
{
}

void Character::Load()
{
	msprite.Load("character.png");
}

void Character::Unload()
{
	msprite.Unload();
}
void Character::Update(float deltaTime, const Map& map)
{
	const float kSpeed = 300.0f;
	float displacementX = 0.0f;
	if(Input_IsKeyDown(Keys::RIGHT))
	{
		displacementX = kSpeed * deltaTime;
	}
	else if(Input_IsKeyDown(Keys::LEFT))
	{
		displacementX =  -kSpeed * deltaTime;
	}

	SRect boundingBox = GetBoundingBox() + SVector2(displacementX, 0.0f);		// make functions out of this! 
	if(displacementX > 0.0f)
	{
		// check rigth
		SLineSegment segment = boundingBox.GetRightSegment();		// the line of the right side of the guy
		SRect collisionBox;
		if(map.TestCollision(segment,collisionBox))
		{
			displacementX -= boundingBox.max.x - collisionBox.min.x;
			mposition.x += (int)(displacementX -1);
		}
		else
		{
			mposition.x += (int)displacementX;
		}
	}
	else if (displacementX < 0.0f)
	{
		// check left
		SLineSegment segment = boundingBox.GetLeftSegment();
		SRect collisionBox;
		if(map.TestCollision(segment,collisionBox))
		{
			displacementX -= (boundingBox.min.x - collisionBox.max.x);
			mposition.x += (int)displacementX;
		}
		else
		{
			mposition.x += (int)(displacementX -1);
		}
	}
	float displacementY = 0.0f;
	
	if(Input_IsKeyDown(Keys::DOWN))
	{
		displacementY =  kSpeed * deltaTime;
	}
	else if(Input_IsKeyDown(Keys::UP))
	{
		displacementY =  -kSpeed * deltaTime;
	}

	boundingBox = GetBoundingBox() + SVector2(0.0f, displacementY);
	if(displacementY < 0.0f)
	{
		// check up
		SLineSegment segment = boundingBox.GetTopSegment();
		SRect collisionBox;
		if(map.TestCollision(segment,collisionBox))
		{
			displacementY -= boundingBox.min.y - collisionBox.max.y;
			mposition.y += (int)(displacementY+1) ;
		}
		else
		{
			mposition.y += (int)displacementY;
		}
	}
	else if(displacementY > 0.0f)
	{
		//check down
		SLineSegment segment = boundingBox.GetBottomSegment();
		SRect collisionBox;
		if(map.TestCollision(segment,collisionBox))
		{
			displacementY -= boundingBox.max.y - collisionBox.min.y;
			mposition.y += (int)(displacementY -1);
		}
		else
		{
			mposition.y += (int)displacementY;
		}
	}

}
void Character::Render(const SVector2& viewoffset)
{
	const int width = msprite.GetWidth();
	const int height = msprite.GetHeight();
	SVector2 offset(width * 0.5f, height *0.5f);
	SVector2 renderPosition = mposition - offset - viewoffset;	// use render position in the setposition

	msprite.SetPosition(renderPosition);
	msprite.Render();
}

SRect Character::GetBoundingBox() const
{
	SRect boundingBox;
	boundingBox.min.x = mposition.x - 22.0f;
	boundingBox.max.x = mposition.x + 22.0f;
	boundingBox.min.y = mposition.y - 35.0f;
	boundingBox.max.y = mposition.y + 35.0f;
	return boundingBox;
}